package com.shenyong.controller;

import com.shenyong.ladmin.entity.Advertising;
import com.shenyong.ladmin.service.AdvertisingService;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Create BY : Qiang
 * GetDate :  2019/12/12 16:24
 * 文件说明 ： UploaderController
 */
@Controller
@RequestMapping("/report")
public class UploaderController {
    private static Logger logger= LoggerFactory.getLogger(UploaderController.class);
    @Value("${portals.upload.image.path}")
    private String imagePath; //图片存储路径
    private String userId="who";  //登陆用户

    @Autowired
    private AdvertisingService advertisingService;
    Advertising adv = new Advertising();
    @RequestMapping("/uploadReport")
    @ResponseBody
    public List<Map<String,String>> upload(@RequestParam MultipartFile[] reportFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String Origin = request.getHeader("Origin");
        response.setHeader("Access-control-Allow-Origin", Origin);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        String day = formatter.format(date);//获取当前天
        String realPath =imagePath; //图片存储路径
        File file = new File(realPath);
        if (!file.exists()) {//文件夹不存在 创建文件夹
            file.mkdirs();
        }
        response.setContentType("text/html; charset=UTF-8");
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        String originalFilename = null;
        for(MultipartFile myfile : reportFile){
            Map<String,String> map = new HashMap<String,String>();
            if(myfile.isEmpty()){
                logger.info("请选择文件后上传!");
                return null;
            }else{
                originalFilename = myfile.getOriginalFilename();
                String extension = FilenameUtils.getExtension(originalFilename);
                if("jpg".equalsIgnoreCase(extension)||"png".equalsIgnoreCase(extension)){
                    originalFilename=userId+"_"+System.currentTimeMillis()+"."+FilenameUtils.getExtension(originalFilename);//修改文件名字
                    adv.setAdvertising_img(originalFilename);
                    try {
                        //上传图片
                        myfile.transferTo(new File(realPath, originalFilename));
                        //保存文件路径
                        map.put("pathUrl",originalFilename);
                        list.add(map);
                        logger.info("load success " + request.getContextPath()+File.separator+"upload"+File.separator+day+File.separator+originalFilename);
                        logger.info("leaving upload!");
                    }catch (Exception e) {
                        logger.info("文件[" + originalFilename + "]上传失败,堆栈轨迹如下");
                        e.printStackTrace();
                        logger.info("文件上传失败，请重试！！");
                        return null;
                    }
                }else{
                    logger.info("load success 只支持jpg,png格式");
                }
            }
        }
        return list;
    }
    @RequestMapping("/uploadImage")
    @ResponseBody
    public String uploadImage(int advertising_id,@RequestParam MultipartFile[] reportFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Map<String,String>> list= upload(reportFile,request,response);
        if (list!=null){
            adv.setAdvertising_id(advertising_id);
            int num=advertisingService.updateImage(adv);
            if (num>0){
                return "上传成功";
            }
        }
        return "上传失败";
    }
}